package org.distributed.transaction.core.repository;

import java.util.concurrent.TimeUnit;

import org.distributed.transaction.core.context.TransactionUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

/**
 * 事务存储器
 */
@Repository
public class TransactionRepository {

	private static final String TM_GROUP_PREFIX = "tm:group:";
	
	private static final Long DEFAULT_EXPIRE_TIME = 300000L;
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * 创建事务组
	 * @param groupId
	 */
	public void createGroup(String groupId) {
		String key = TM_GROUP_PREFIX + groupId;
		redisTemplate.opsForHash().put(key, "root", "");
		redisTemplate.expire(key, DEFAULT_EXPIRE_TIME, TimeUnit.MILLISECONDS);
	}
	
	public void joinGroup(String groupId, TransactionUnit transactionUnit) {
		String key = TM_GROUP_PREFIX + groupId;
		redisTemplate.opsForHash().put(key, transactionUnit.getUnitId(), transactionUnit);
	}
	
	/**
	 * 关闭事务组
	 * @param groupId
	 */
	public void clearGroup(String groupId) {
        redisTemplate.delete(TM_GROUP_PREFIX + groupId);
    }
	
}
